<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/24
 * Time: 15:28
 */

namespace App\Game\Traits;

use App\Models\Def\MainGamePlat;
use App\Models\Inf\Player;
use Crypt_RSA;
use Carbon\Carbon;

trait EbetTrait
{
    /**
     * gameapi
     * 2018/9/24 13:55
     * Administrator
     * getSign
     * 生成签名
     * @param $plaintext
     * @return string
     */
    public function getSign($plaintext)
    {
        $rsa = new Crypt_RSA();
        $rsa->loadKey($this->privateKey);//xxx 私钥匙
        $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
        $rsa->setHash("md5");
        $signature = $rsa->sign($plaintext);
        return base64_encode($signature);
    }

    /**
     * gameapi
     * 2018/9/24 13:55
     * Administrator
     * agRequest
     * 封装ag得请求
     * @param $action
     * @return string
     */
    public function agRequest($action)
    {
        //去掉用户名前缀
        if (isset($action['username'])){
            $action['username'] = str_replace($this->pre,'',$action['username']);
        }
        ksort($action,SORT_NATURAL);

        $action=json_encode($action);
        $action=openssl_encrypt($action,'AES-128-CBC',$this->appKey,OPENSSL_RAW_DATA ,substr($this->appKey,0,16));

        $post=[];
        $post['appid']=$this->appId;
        $post['ver']='v1';
        $post['params']=urlencode(base64_encode($action));
        $result=$this->curlApiInfo($this->gameUrl,$post);
        return $result;
    }

    /**
     * gameapi
     * 2018/9/24 15:28
     * Administrator
     * prepareTransfer
     * 预备转账
     * @param $accountUserName
     * @param $type
     * @param $actype
     * @param $price
     * @param $transferid
     * @return array
     */
    public function prepareTransfer($accountUserName, $type, $actype, $price, $transferid,$mainGamePlatId)
    {
        $player = Player::where('username', $accountUserName)->where('main_game_plats_id', $mainGamePlatId)->first();
        $action = [
            'platform' => 'EBET',
            'method' => $type,
            'username' => $accountUserName,
            'password' => $player->password,
            'orderid' => $this->cagent . $transferid,
            'amount' => $price,
            'currency' => 'CNY',
        ];

        $output = $this->agRequest($action);

        if ($output['status']==0) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '预备转账失败，错误原因：CURL 未能执行成功 ' . $output['data']];
        }

        if ($output['header']==0) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '预备转账失败，错误原因：对方服务器 未能执行成功' . $output['data']];
        }
        $data = $this->strToArray($output['data']);
        if (!is_array($data) || $data['code'] != 0){
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '预备转账失败，错误原因：'.$data['message'].'...'.$accountUserName];
        }
        return ['success' => true, 'data' => ['transferid' => $this->cagent . $transferid, 'transfer_state' => 1], 'message' => ''];
    }

    /**
     * gameapi
     * 2018/9/24 15:28
     * Administrator
     * transferConfirm
     * 确认转账
     * @param $accountUserName
     * @param $type
     * @param $actype
     * @param $price
     * @param $transferid
     * @return array
     */
    public function transferConfirm($accountUserName, $type, $actype, $price, $transferid,$mainGamePlatId)
    {
        $player = Player::where('username', $accountUserName)->where('main_game_plats_id', $mainGamePlatId)->first();
        $action = [
            'platform' => 'EBET',
            'method' => $type,
            'username' => $accountUserName,
            'password' => $player->password,
            'orderid' => $this->cagent . $transferid,
//            'amount' => round($price, 2),
            'currency' => 'CNY',
        ];

        $output = $this->agRequest($action);

        if ($output['status']==0) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '确认转账失败，错误原因：CURL 未能执行成功 ' . $output['data']];
        }

        if ($output['header']==0) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '确认转账失败，错误原因：对方服务器 未能执行成功' . $output['data']];
        }
        $data = $this->strToArray($output['data']);
        if (!is_array($data) || $data['code'] != 0){
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '确认转账失败，错误原因：'.$data['message'].'...'.$accountUserName];
        }
        return ['success' => true, 'data' => [], 'message' => ''];
    }

    /**
     * gameapi
     * 2018/9/24 17:27
     * Administrator
     * changeUpdateFiled
     * 变更修改字段
     * @param array $apiData
     */
//    public function changeUpdateFiled(array $apiData)
//    {
//        if (array_key_exists('dataType', $apiData)) {
//            if ($apiData['dataType'] === "HSR") {
//                $this->updateFiled = config('game.' . $this->platName)['updateFiled'][$apiData['dataType']];
//            }
//        }
//    }

    /**
     * gameapi
     * 2018/9/24 17:35
     * Administrator
     * apiDataParse
     * 字段解析
     * @param array $apiData
     * @param array $data
     * @return array
     */
    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->statusParse($apiData, $data);
        $data = $this->gameCode($data);
        return $data;
    }

    /**
     * gameapi
     * 2018/9/24 17:36
     * Administrator
     * statusParse
     * 解析状态字段
     * @param array $apiData
     * @param array $data
     * @return array
     */
    private function statusParse(array $apiData, array $data)
    {
        if (array_key_exists('standard_settle', $apiData)) {
            switch ($apiData['standard_settle']) {
                case '1':
                    $data['status'] = 1;
                    break;
                case '0':
                    $data['status'] = 0;
                    break;
                default:
                    $data['status'] = -1;
                    break;
            }
        }
        return $data;
    }

    /**
     * gameapi
     * 2018/9/27 23:03
     * Administrator
     * dataFilter
     * 数据过滤
     * @param array $apiData
     * @param array $data
     * @return array|null
     */
    private function dataFilter(array $apiData, array $data)
    {
        if (array_key_exists('dataType', $apiData)) {
            if (in_array($apiData['dataType'], ['BR', 'EBR', 'HSR'])) {
                return $data;
            }
        }
        return null;
    }

    private function gameCode(array $data)
    {
        if (array_key_exists('game_code', $data)) {
            $data['game_code'] = str_before($data['game_code'], '-');
        }
        return $data;
    }

}